# Generated manually to generate pinyin for existing foods

from django.db import migrations
from xpinyin import Pinyin
import re

def generate_pinyin_for_foods(apps, schema_editor):
    """为现有的食物生成拼音"""
    FoodItem = apps.get_model('main', 'FoodItem')
    pinyin = Pinyin()
    
    for food in FoodItem.objects.all():
        if not food.name_pinyin:  # 如果没有拼音，则生成
            food.name_pinyin = pinyin.get_pinyin(food.name, '')
            food.name_py_abbr = ''.join([
                w[0] for w in re.findall(r'[a-z]+', food.name_pinyin)
            ])
            # 直接更新数据库，不触发save方法
            FoodItem.objects.filter(id=food.id).update(
                name_pinyin=food.name_pinyin,
                name_py_abbr=food.name_py_abbr
            )

def reverse_generate_pinyin(apps, schema_editor):
    """回滚：清空拼音字段"""
    FoodItem = apps.get_model('main', 'FoodItem')
    FoodItem.objects.update(name_pinyin='', name_py_abbr='')

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0009_add_pinyin_fields'),
    ]

    operations = [
        migrations.RunPython(generate_pinyin_for_foods, reverse_generate_pinyin),
    ]

